package com.link.base.base.position.controller;

import com.link.base.base.user.model.User;
import com.link.base.base.dept.model.Department;
import com.link.base.base.dept.service.DepartmentService;
import com.link.base.base.position.model.ApiPosition;
import com.link.base.base.position.model.Position;
import com.link.base.base.position.service.PositionService;
import com.link.base.base.user.service.UserService;
import com.link.base.core.apiutils.ApiBasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author  朱泊阳
 * @date:   2018/11/12 17:15
 * @version 1.0
 * @comment interface微服务调用接口
 */

@Controller("ApiPositionApiController")
@RequestMapping("/linkApi/postn")
public class MicroPositionController extends ApiBasicController<Position> {

    @Resource
    private PositionService positionService;

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private UserService userService;

    @Override
    public BasicService<Position> getBasicService() throws Exception {
        return positionService;
    }

    @RequestMapping(value = "/upsert", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upsert(@RequestBody ApiPosition model, HttpServletRequest request,
                                      HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {

            Position postn = getPosition(model);
            if (postn == null) {
                postn = new Position();
                postn.setRow_status("NEW");
                setPostnParent(model, postn);
                Long id = keyGenerateService.keyGenerate();
                postn.setId(id);
            } else {
                postn.setRow_status("UPDATE");
                setPostnParent(model, postn);
            }

            ApiBasicController.apiCopyProperties(model, postn);


            //校验传入的主要负责人
            //如果传入的主要负责人不为空，则校验是否存在，
            //不存在则报错
            Long userId = model.getUserId();
            if (userId != null && !checkUserExists(userId)) {
                throw new ServiceException("POSITION-006",userId.toString());
            }
            Department dept = getDept(model);
            Long parentPosId = postn.getParentPositionId();
            postn.setDeptId(dept.getId());
            postn.setParentPositionId(parentPosId);
            positionService.upsert(postn);
            result.put("success", true);
            result.put("crmId", postn.getId());
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>
     * 获取职位所属部门/组织信息
     * </p>
     *
     * @author yrf
     * @param model
     * @return
     * @throws Exception
     */
    private Department getDept(ApiPosition model) throws Exception {
        String deptIntegrationId = model.getDeptIntegrationId();
        if (deptIntegrationId == null) {
            throw new ServiceException("POSITION-007");
        }
        Department dept = null;
        Department example = new Department();
        example.setAnonymousFlag("Y");
        example.setPageFlag(false);
        example.setIntegrationId(deptIntegrationId);

        List<Department> list = departmentService.queryByExamplePage(example);
        if (list == null || list.size() == 0) {
            throw new ServiceException("POSITION-008",deptIntegrationId);
        } else if (list.size() > 1) {
            throw new ServiceException("POSITION-009",deptIntegrationId);
        } else {
            dept = list.get(0);
        }
        return dept;
    }

    /**
     * <p>
     * 获取职位
     * </p>
     *
     * @author yrf
     * @param model
     * @return
     * @throws Exception
     */
    public Position getPosition(ApiPosition model) throws Exception {
        Position postn = null;
        Long crmId = model.getCrmId();
        String integrationId = model.getIntegrationId();
        if (StringUtils.isBlank(integrationId)) {
            throw new ServiceException("POSITION-010");
        }
        if (crmId != null) {
            Position example = new Position();
            example.setAnonymousFlag("Y");
            example.setId(crmId);

            postn = positionService.queryById(example);
            if (postn == null) {
                throw new ServiceException("POSITION-011",crmId.toString());
            } else if (!integrationId.equals(postn.getIntegrationId())) {
                throw new ServiceException("POSITION-012");
            }
        } else {
            Position example = new Position();
            example.setIntegrationId(integrationId);
            example.setPageFlag(false);

            List<Position> list = positionService.queryByExamplePage(example);
            if (list != null && list.size() > 0) {
                if (list.size() == 1) {
                    postn = list.get(0);
                } else {
                    throw new ServiceException("POSITION-013",integrationId);
                }
            }
        }
        return postn;
    }

    /**
     * @author huanglongjian
     * @param model
     * @param postn
     * @throws Exception
     * @Description 设置职位的父职位
     * @
     */
    private void setPostnParent(ApiPosition model, Position postn) throws Exception {
        // 判断，如果传了父集成id，则通过父的集成id查询父职位，否则直接查询root职位
        if ("".equals(model.getParentIntegrationId()) || model.getParentIntegrationId() == null) {
            Position queryTmp = new Position();
            Position restTmp = positionService.queryRoot(queryTmp);
            Long rootId = restTmp.getId();
            postn.setParentPositionId(rootId);
        } else {
            Position queryTmp = new Position();
            queryTmp.setIntegrationId(model.getParentIntegrationId());
            Position restTmp = positionService.queryByIntegrationId(queryTmp);
            Long rootId = restTmp.getId();
            postn.setParentPositionId(rootId);
        }
    }

    /**
     * @author huanglongjian
     * @Description 校验职位的主要负责人是否存在，不存在则报错
     * @Return false 不存在， true 不存在
     */
    private boolean checkUserExists(Long empId) throws Exception {
        User userQuery = new User();
        userQuery.setId(empId);
        User user = userService.queryById(userQuery);
        if (user == null) {
            return false;
        }
        return true;

    }
}
